<template>
  <div>
    <input type="file" @change="handleFileUpload" />
    <button @click="submitImage">上传图片</button>
    <div v-if="previewURL" class="image-preview">
      <img :src="previewURL" alt="Image Preview" />
    </div>
    <LayoutSection flex-content :title="overviewData.title">
      <div style="height: 100%; flex: 1; border: 1px solid ;">
        <img class="full-size-image" :src="imageURL" />
      </div>
    </LayoutSection>
  </div>

</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useResultStore } from '@/modules/Result/store'
import { useRoute } from 'vue-router'
import axios from 'axios'

const resultStore = useResultStore()
const route = useRoute()
const overviewData = computed(() => resultStore.overviewData)
const imageURL = ref('')
const previewURL = ref('')

async function init() {
  const { error, data } = await resultStore.getResultOverview({
    projectId: route.params.projectId
  })
  if (error) return
  console.log('overview', data)
}
const selectedFile = ref(null)

function handleFileUpload(event) {
  selectedFile.value = event.target.files[0]
  previewURL.value = URL.createObjectURL(selectedFile.value)
}

async function submitImage() {
  if (!selectedFile.value) return
  const formData = new FormData()
  formData.append('image', selectedFile.value)
  const response = await axios.post('http://localhost:8100/api/upload-image', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (response.data.success) {
    // 注意：这里添加了完整的域和端口
    imageURL.value = `http://localhost:8100${response.data.imageURL}`
  }
}

init()
</script>

<style lang="scss" scoped>
.wrap-result-overview-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 360px) 528px;
  grid-gap: 16px;
  padding-bottom: 16px;

  .grid-last {
    grid-column-start: span 2;
  }

  .fitting-operate {
    color: $color-primary;
    cursor: pointer;
  }
}

.full-size-image {
  width: 100%;
  height: 100%;
  // object-fit: cover;  //这个是保持原始比例 但是可能会被裁剪
}
.image-preview img {
  width: 100%;
  max-width: 500px; /* Adjust as needed */
}
</style>
